package cn.windy.samary.module.shiro.filter;

import cn.windy.samary.module.admin.enums.EnumUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author zyl
 * @date 2018/5/14 9:05
 */
public class CustomAccessFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String servletPath = httpServletRequest.getServletPath();

        if (subject.hasRole(EnumUtil.ROLE_SYSTEM)) {
            return true;
        }

        if (subject.isAuthenticated()) {
            if ("/admin/index".equals(servletPath) || "/403".equals(servletPath)) {
                return true;
            } else {
                return subject.isPermitted(servletPath);
            }
        }

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.issueRedirect(request, response, "/403");
        return false;
    }
}
